<template>
  <form
    class="box-content"
    @submit.prevent="handleSearch"
    method="get"
    @contextmenu.stop
  >
    <div class="submit" :style="searchStyle">
      <!-- 左侧引擎选择 -->
      <div class="login" @click="isPopupVisible = true">
        <img class="iconurl" :src="currentEngine.icon" />
        <img class="icon" src="@/assets/icon/caret-right.png" />
      </div>

      <!-- 输入框 -->
      <input
        v-model="searchQuery"
        class="input"
        :autofocus="shouldFocus"
        placeholder="请输入搜索内容"
        @input="onInput"
        @keydown="onKeyDown"
        @focus="onFocus"
        @blur="onBlur"
      />

      <!-- 搜索按钮 -->
      <div class="searchicon" @click="handleSearch">
        <span class="iconfont icon-sousuo" />
      </div>
    </div>

    <!-- 下拉建议 -->
    <div v-if="showPanel" class="content" :style="contentlist">
      <ul v-if="renderList.length" @click="onListClick">
        <li
          v-for="(item, idx) in renderList"
          :key="idx"
          :class="{ activeSS: activeIdx === idx }"
          @mouseenter="
            activeIdx = idx;
            hoverIdx = idx;
          "
          @mouseleave="
            activeIdx = -1;
            hoverIdx = -1;
          "
        >
          <!-- 历史记录 -->
          <template v-if="item.isHistory">
            <div class="historylist">
              <span class="iconfont icon-faxian" />
              <span class="searchvalue">{{ item.search }}</span>
              <span v-if="hoverIdx !== idx" class="searchtime">{{
                item.timeText
              }}</span>
              <span v-else class="delete" :data-del="item.search"> 删除 </span>
            </div>
          </template>

          <!-- 联想建议 -->
          <template v-else>
            {{ item.text }}
          </template>
        </li>
      </ul>
      <!-- 兜底：没有历史记录 -->
      <div v-else class="empty-tip">
        <span>暂无搜索记录</span>
      </div>
    </div>
  </form>

  <!-- 引擎选择弹窗 -->
  <full-screen-popup
    :visible="isPopupVisible"
    :width="800"
    :height="400"
    @update:visible="isPopupVisible = $event"
  >
    <div class="searchbox">
      <div
        v-for="eng in searchEngines"
        :key="eng.name"
        class="card-box"
        @click="setEngine(eng)"
      >
        <img class="card" :src="eng.icon" />
        <span>{{ eng.name }}</span>
      </div>
    </div>
  </full-screen-popup>
</template>

<script setup>
import { computed, ref, shallowRef } from "vue";
import { useStore } from "vuex";
import { debounce } from "@/util/debounce";
import { getFormattedCurrentTime, getTimeDifference } from "@/util/time";
import FullScreenPopup from "../FullScreenPopup/";
import searchEngines from "../../config/search";

/* ===== 状态 ===== */
const store = useStore();

const searchQuery = ref("");
const activeIdx = ref(-1);
const hoverIdx = ref(-1);
const showPanel = ref(false);
const isPopupVisible = ref(false);

/* ===== 计算属性（只读） ===== */
const shouldFocus = computed(() => store.getters.getshouldFocus);
const currentEngine = computed(
  () => store.getters.getsearch || searchEngines[0]
);
const searchStyle = computed(() => {
  const h = store.getters.getSearchHeight;
  const r = store.getters.getSearchRadius;
  const t = store.getters.getSearchTransparency;
  return {
    height: h + "px",
    borderRadius: r + "px",
    backgroundColor: `rgba(255,255,255,${t / 100})`,
    "--panel-bg": `rgba(240,240,240,${t / 100})`,
  };
});
const contentlist = computed(() => {
  const t = store.getters.getSearchTransparency;
  return {
    "--panel-bg": `rgba(240,240,240,${t / 100})`,
  };
});

const historyEnabled = computed(() => store.getters.gethistory);
const rawHistory = computed(() =>
  store.getters.gethistorylist.map((i) => ({
    ...i,
    timeText: getTimeDifference(i.time),
    isHistory: true,
    showDel: false,
  }))
);

/* ===== 渲染列表（建议 + 历史） ===== */
const renderList = computed(() => {
  if (searchQuery.value) {
    return suggestions.value.map((t) => ({ text: t, isHistory: false }));
  }
  return historyEnabled.value ? rawHistory.value : [];
});

/* ===== 建议请求（防抖 200ms） ===== */
const suggestions = shallowRef([]);
const fetchSuggestions = debounce(() => {
  const q = searchQuery.value.trim();
  if (!q) return resetSuggestions();
  fetch(`https://www.baidu.com/sugrec?prod=pc&wd=${encodeURIComponent(q)}`, {
    mode: "cors",
  })
    .then((r) => r.json())
    .then((d) => {
      suggestions.value = (d.g || []).map((i) => i.q);
    })
    .catch(() => {
      /* 静默失败 */
    });
}, 200);

function resetSuggestions() {
  suggestions.value = [];
  activeIdx.value = -1;
}

/* ===== 事件 ===== */
function onInput() {
  activeIdx.value = -1;
  fetchSuggestions();
}

function onKeyDown(e) {
  const len = renderList.value.length;
  if (!len) return;
  if (e.key === "ArrowUp") {
    activeIdx.value = (activeIdx.value - 1 + len) % len;
  } else if (e.key === "ArrowDown") {
    activeIdx.value = (activeIdx.value + 1) % len;
  } else if (e.key === "Enter") {
    e.preventDefault();
    // 1) 如果用户用上下键选中了联想词 / 历史记录
    if (renderList.value.length && activeIdx.value >= 0) {
      selectItem(renderList.value[activeIdx.value]);
    }
    // 2) 否则直接用输入框里的内容搜索
    else if (searchQuery.value.trim()) {
      handleSearch();
    }
  }
}

function onFocus() {
  showPanel.value = true;
  if (!searchQuery.value && historyEnabled.value) {
    resetSuggestions();
  }
}

function onBlur() {
  setTimeout(() => (showPanel.value = false), 350);
}

function selectItem(item) {
  searchQuery.value = item.isHistory ? item.search : item.text;
  handleSearch();
}

function handleSearch() {
  const q = searchQuery.value.trim();
  if (!q) return;
  store.commit("historylist", { search: q, time: getFormattedCurrentTime() });
  const url = `${currentEngine.value.search}${encodeURIComponent(q)}`;
  store.getters.getnewtab ? window.open(url, "_blank") : (location.href = url);
  searchQuery.value = "";
  resetSuggestions();
}

function setEngine(engine) {
  store.commit("search", engine);
  isPopupVisible.value = false;
}

/* 事件委托删除 */
function onListClick(e) {
  const li = e.target.closest("li");
  if (!li) return;
  const idx = Array.from(li.parentNode.children).indexOf(li);
  const item = renderList.value[idx];
  // 如果点的是删除按钮
  if (e.target.classList.contains("delete") || e.target.closest(".delete")) {
    store.commit("deleteSearchRecord", item.search);
    return;
  }
  // 否则就是点击整行
  searchQuery.value = item.isHistory ? item.search : item.text;
  handleSearch();
}
</script>

<style scoped>
.box-content {
  width: 100%;
  height: 100%;
  position: relative;
}

.submit {
  width: 100%;
  height: 100%;
  border-radius: 25px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  overflow: hidden;
  box-shadow: 0px 0px 5px rgba(0, 0, 0, 0.3);
  background-color: rgba(255, 255, 255, 0.97);
}

.box-content .submit .login {
  width: 60px;
  height: 100%;
  border-radius: 10px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.box-content .submit .login .iconurl {
  width: 40px;
  height: 40px;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 10px;
}

.box-content .submit .login .iconurl img {
  width: 20px;
  height: 20px;
}

.box-content .submit .login .icon {
  width: 17px;
  height: 17px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.box-content .submit .login .icon img {
  width: 100%;
  height: 100%;
  transform-origin: 50% 50%;
  transition: transform 0.5s ease;
}

.box-content .submit .login:hover {
  background-color: rgba(240, 240, 240, 0.8);
}

.box-content .submit .input {
  all: unset;
  flex: 1;
  height: 100%;
  text-align: left;
  background: transparent;
  font-family: "Arial", sans-serif;
  font-size: 16px;
}

.box-content .submit .input:focus::placeholder {
  visibility: hidden;
}

.box-content .submit .searchicon {
  width: 50px;
  height: 100%;
  display: flex;
  border-radius: 25px;
  justify-content: center;
  align-items: center;
}

.box-content .submit .searchicon .iconfont {
  font-size: 23px;
}

.box-content .content {
  width: 100%;
  border-radius: 10px;
  background-color: var(--panel-bg);
  backdrop-filter: blur(25px);
  position: absolute;
  margin-top: 15px;
  margin-left: 0px;
  border: 1px solid var(--panel-bg); /* 轻微的边框 */
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1); /* 微弱的阴影，给人立体感 */
  font-family: "Arial", sans-serif;
  z-index: 99;
}

.box-content .content::after {
  content: "";
  width: 0;
  height: 0;
  border-left: 10px solid transparent;
  border-right: 10px solid transparent;
  border-bottom: 10px solid var(--panel-bg);
  position: absolute;
  top: -10px;
  left: 20px;
}

.activeSS {
  background-color: #f4f4f4; /* 背景变色 */
  color: #007bff;
}

.historylist {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  width: 100%;
}

.delete {
  background-color: #ddd;
  font-size: 12px;
  color: #333;
  border-radius: 4px;
  cursor: pointer;
  display: inline-block;
}

.searchtime {
  color: #575757;
  font-size: 12px;
}

.historylist > span {
  flex: 0 0 auto;
}

.historylist > span:nth-child(1) {
  width: 5%;
}

.historylist > span:nth-child(2) {
  text-align: left;
  width: 85%;
}

.historylist > span:nth-child(3) {
  width: 10%;
}

/* 搜索建议列表项 */
.content ul {
  list-style: none;
  margin: 0;
  padding: 0;
  margin: 10px 0px;
}

/* 列表项 */
.content li {
  padding: 10px 20px; /* 内边距，使内容更舒适 */
  cursor: pointer; /* 鼠标悬停时显示为可点击 */
  transition: background-color 0.3s, color 0.3s; /* 平滑的颜色过渡 */
}

/* 鼠标悬停效果 */
.content li:hover {
  background-color: #f4f4f4; /* 背景变色 */
  color: #007bff; /* 鼠标悬停时文字变色 */
}

.empty-tip {
  text-align: center;
  padding: 20px 0;
  color: #999;
  min-height: 60px; /* 避免塌陷 */
  display: flex;
  align-items: center;
  justify-content: center;
}

.searchbox {
  width: 100%;
  height: 100%;
  padding: 5px;
  overflow: auto;
  display: flex;
  justify-content: flex-start;
  align-content: flex-start;
  flex-wrap: wrap;
  position: relative;
}

.card-box {
  width: 50px;
  height: 70px;
  margin: 5px 10px;
  text-align: center;
}

.card-box span {
  margin: 10px 0px 0px 0px;
  line-height: 20px;
  width: 50px;
  white-space: nowrap;
  overflow: hidden; /* 隐藏溢出的内容 */
  text-overflow: ellipsis; /* 显示省略号 */
}

@media (max-width: 620px) {
  .searchbox {
    width: 90%;
  }
}

.card {
  background: linear-gradient(135deg, #d8d8d8, #f0f8ff);
  width: 50px;
  height: 50px;
  border-radius: 10px; /* 圆角 */
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1), 0 6px 6px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease; /* 平滑过渡 */
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;
}

.searchbox img {
  width: 40px;
  height: 40px;
}

.card:hover {
  transform: translateY(-10px); /* 向上移动 */
  box-shadow: 0 15px 30px rgba(0, 0, 0, 0.2), 0 10px 10px rgba(0, 0, 0, 0.12);
}
</style>
